import { StyleSheet, Text, View, ScrollView, Pressable, Image, TextInput } from 'react-native';
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import ECharts from 'react-native-echarts-pro';
import { useFocusEffect } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import Modal from 'react-native-modal';
import Icon from 'react-native-vector-icons/Ionicons';
import dayjs from 'dayjs';
import moment from 'moment';
import 'moment/locale/zh-cn'; // 中文
import isoWeek from 'dayjs/plugin/isoWeek';
import { px2dp, scale, width } from '~/utils/px2dp';
import { getStepData, setGoalApi } from '~/api/deviceToolsApi';
import { observer, deviceStore, userStore, appStore } from '~/store';
import { calcStepData } from '~/utils/helpers';
import { ProgressBarBySport } from './ProgressBar';

interface Props {
    selectIndex: number;
}
dayjs.extend(isoWeek);

const tabWidth = (width - px2dp(120)) / 3; // 每个 tab 的宽度
export default observer((props: Props) => {
    moment.locale(appStore.app.language == 'zh' ? 'zh-cn' : 'en');
    const { t } = useTranslation();
    const { selectIndex } = props;
    const { userBindDeviceData, autoConnectDeviceSn } = userStore;
    const { device } = deviceStore;
    const deviceInfo = useMemo(() => {
        let res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
        if (deviceStore.device?.connectedDeviceStatus == 1) {
            res = userBindDeviceData.find((item) => item.device_sn == device?.connectDevice?.device_sn);
        } else {
            if (autoConnectDeviceSn) {
                res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
            } else {
                res = userBindDeviceData[0];
            }
        }
        return res;
    }, [
        userBindDeviceData,
        autoConnectDeviceSn,
        deviceStore.device?.connectedDeviceStatus,
        device?.connectDevice?.device_sn,
    ]);
    // 切换table
    const tableData = [
        { id: 1, title: t('SportData.t1') },
        { id: 2, title: t('SportData.t2') },
        { id: 3, title: t('SportData.t3') },
    ];
    const [activeIndex, setActiveIndex] = useState(1);
    const changeTable = (id) => {
        setActiveIndex(id);
    };
    // 设置目标步数
    const [visible, setVisible] = useState(false);
    const [number, setNumber] = useState('');
    const saveSportGoal = () => {
        setGoalApi({ deviceId: deviceInfo?.device_id, number, device_sn: deviceInfo?.device_sn }).then((res) => {});
        setVisible(false);
        getData();
    };
    // 获取今日数据
    const [stepInfo, setStepInfo] = useState({
        calories: '',
        distance: '',
        goal: 3500,
        goalCalories: '',
        goalDistance: '',
        steps: '',
        time: { hours: 0, minutes: 0 },
    });
    const [stepProGress, setStepProGress] = useState(0);
    const [caloriesProGress, setCaloriesProGress] = useState(0);
    const [stepDatas, setStepDatas] = useState({ sum: 0, max: 0, lastAvg: 0, avg: 0 });
    const convertToCalories = (t) => t * 0.048;
    const processData = (array) => {
        let xData: string[] = [];
        let yData: any[] = [];
        let cData: any[] = [];
        if (activeIndex === 2) {
            const weekDays = moment.weekdaysShort(appStore.app.language === 'zh' ? true : false);
            xData = weekDays;
            const dataMap: Record<string, number> = {};
            array.forEach((item) => {
                const timestamp = Number(item.time) * 1000;
                const key = moment(timestamp).format('ddd');
                dataMap[key] = Number(item.t);
            });
            yData = xData.map((day) => dataMap[day] || 0);
            cData = yData.map((t) => convertToCalories(t));
        } else if (activeIndex === 3) {
            const now = moment();
            const daysInMonth = now.daysInMonth(); // 本月总天数
            xData = Array.from({ length: daysInMonth }, (_, i) => String(i + 1)); // ['1','2',...]

            const dataMap: Record<string, number> = {};
            array.forEach((item) => {
                const timestamp = Number(item.time) * 1000;
                const key = moment(timestamp).format('D'); // 取日号
                dataMap[key] = Number(item.t);
            });

            yData = xData.map((day) => dataMap[day] || 0);
            cData = yData.map((t) => convertToCalories(t));
        }

        return { xData, yData, cData };
    };
    const getData = (type = 1, startTime = dayjs().valueOf(), endTime = dayjs().valueOf()) => {
        const obj = {
            deviceId: deviceInfo?.device_id,
            type,
            device_sn: deviceInfo?.device_sn,
            startTime,
            endTime,
        };
        getStepData(obj).then((res) => {
            if (res.code == 200) {
                if (type == 1) {
                    const { myGoal, mySteps } = res?.returnData?.userTodayData;
                    const stepGerss = myGoal ? mySteps / myGoal : 2000;
                    setStepProGress(stepGerss);
                    setNumber(myGoal || 2000);
                    const result: any = calcStepData(myGoal > 0 ? myGoal : 2000, mySteps);
                    const caloriesGerss = myGoal ? result.calories / result.goalCalories : 100;
                    setCaloriesProGress(caloriesGerss);
                    setStepInfo(result);
                } else {
                    const { avg, lastAvg, list, max, sum } = res.returnData;
                    const { xData, yData, cData } = processData(list);
                    const obj = { avg, lastAvg, max, sum };
                    const option = createOption(
                        xData.length > 0 ? xData : [t('SportData.t4')],
                        yData.length > 0 ? yData : [t('SportData.t4')],
                    );
                    setStepOption(option);
                    const caloriesOpt = createCaloriesOption(
                        xData.length > 0 ? xData : [t('SportData.t4')],
                        cData.length > 0 ? cData : [t('SportData.t4')],
                    );
                    console.log('xData, yData, cData', xData, yData, cData);
                    setCaloriesOption(caloriesOpt);
                    setStepDatas(obj);
                }
            }
        });
    };
    // 行走柱状图
    const [stepOption, setStepOption] = useState({});
    const createOption = (xAxisData: string[], yAxisData: number[]) => ({
        grid: {
            left: '2%',
            right: '2%',
            top: '12%',
            bottom: '2%',
            containLabel: true,
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
                lineStyle: {
                    type: 'dashed',
                    color: '#ccc',
                },
            },
            backgroundColor: '#584F5E',
            borderRadius: 6,
            padding: 10,
            textStyle: {
                color: '#fff',
            },
            formatter: '{b}<br/>{c}',
            rich: {
                c: {
                    fontSize: 18, // 🔍 放大字体
                    fontWeight: 'bold',
                    color: '#fff',
                    lineHeight: 28,
                },
            },
        },
        title: {
            text: t('SportData.t5'),
            top: 10,
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 16,
            },
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: {
                lineStyle: {
                    color: '#ccc',
                    type: 'dashed',
                },
            },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
        },
        yAxis: {
            type: 'value',
            axisLine: { show: true },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
        },
        series: [
            {
                name: 't',
                type: 'bar',
                data: yAxisData,
                itemStyle: {
                    color: '#F9A427',
                },
            },
        ],
    });

    // 卡路里
    const [caloriesOption, setCaloriesOption] = useState({});
    const createCaloriesOption = (xAxisData: string[], yAxisData: number[]) => ({
        title: {
            text: t('SportData.t6') + '(kcal)',
            top: 10,
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 16,
            },
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
                lineStyle: {
                    type: 'dashed',
                    color: '#ccc',
                },
            },
            backgroundColor: '#584F5E',
            borderRadius: 6,
            padding: 10,
            textStyle: {
                color: '#fff',
            },
            formatter: '{b}<br/>{c} kcal',
            rich: {
                c: {
                    fontSize: 18, // 🔍 放大字体
                    fontWeight: 'bold',
                    color: '#fff',
                    lineHeight: 28,
                },
            },
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: {
                lineStyle: {
                    color: '#ccc',
                    type: 'dashed',
                },
            },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
        },
        yAxis: {
            type: 'value',
            axisLine: { show: true },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
            max: 200,
        },
        grid: {
            left: '5%',
            right: '5%',
            top: '18%',
            bottom: '2%',
            containLabel: true,
        },
        series: [
            {
                data: yAxisData,
                smooth: 1,
                type: 'line',
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                    color: 'red',
                    width: 2,
                },
                itemStyle: {
                    color: '#fff', // 填充颜色（中间空心）
                    borderColor: 'red', // 边框颜色
                    borderWidth: 2,
                },
            },
        ],
    });
    // 周、月
    const [currentDate, setCurrentDate] = useState(dayjs());
    const [displayText, setDisplayText] = useState('');
    const updateDisplay = (date) => {
        if (activeIndex === 2) {
            // 周视图
            let startTime, endTime;
            const startOfWeek = date.startOf('isoWeek');
            const endOfWeek = date.endOf('isoWeek');
            startTime = Math.floor(startOfWeek.valueOf() / 1000); // 秒级
            endTime = Math.floor(endOfWeek.valueOf() / 1000); // 秒级
            setDisplayText(`${startOfWeek.format('MM/DD')} - ${endOfWeek.format('MM/DD')}`);
            getData(2, startTime, endTime);
        } else if (activeIndex === 3) {
            // 月视图
            let startTime, endTime;
            const startOfMonth = date.startOf('month');
            const endOfMonth = date.endOf('month');
            setDisplayText(date.format('YYYY-MM'));
            startTime = Math.floor(startOfMonth.valueOf() / 1000); // 秒级
            endTime = Math.floor(endOfMonth.valueOf() / 1000); // 秒级
            getData(3, startTime, endTime);
        } else {
            // 日视图
            getData(1, dayjs().valueOf(), dayjs().valueOf());
        }
    };
    const handlePrev = () => {
        if (activeIndex === 2) {
            setCurrentDate(currentDate.subtract(1, 'week'));
        } else if (activeIndex === 3) {
            setCurrentDate(currentDate.subtract(1, 'month'));
        }
    };

    const handleNext = () => {
        if (activeIndex === 2) {
            setCurrentDate(currentDate.add(1, 'week'));
        } else if (activeIndex === 3) {
            setCurrentDate(currentDate.add(1, 'month'));
        }
    };
    useFocusEffect(
        useCallback(() => {
            if (selectIndex == 1) {
                updateDisplay(currentDate);
            }
        }, [currentDate, activeIndex, selectIndex, deviceInfo]),
    );

    return (
        <ScrollView
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.contentStyle}
            stickyHeaderIndices={[0]}>
            <View style={[styles.nav]}>
                <View style={[styles.row, styles.between]}>
                    {tableData.map((item: any, index) => {
                        return (
                            <Pressable
                                onPress={() => changeTable(item.id)}
                                key={index}
                                style={[
                                    styles.listTable,
                                    activeIndex === item.id && { backgroundColor: 'rgba(216, 216, 216, 0.32)' },
                                ]}>
                                <Text
                                    style={[
                                        styles.listTableText,
                                        activeIndex === item.id && { fontWeight: 'bold', color: '#000' },
                                    ]}>
                                    {item?.title}
                                </Text>
                            </Pressable>
                        );
                    })}
                </View>
            </View>
            <View style={styles.content}>
                {activeIndex == 1 ? (
                    <View>
                        <Pressable style={[styles.card, styles.row, styles.between]} onPress={() => setVisible(true)}>
                            <View style={{ marginLeft: px2dp(32) }}>
                                <Text style={styles.t1}>{t('SportData.t20')}</Text>
                                <View style={[styles.row, { marginTop: px2dp(12) }]}>
                                    <Text style={styles.goalSteps}>{stepInfo.goal}</Text>
                                    <Text style={styles.tips}>
                                        {parseInt(stepInfo.steps) >= stepInfo.goal
                                            ? t('SportData.t7')
                                            : t('SportData.t8')}
                                    </Text>
                                </View>
                            </View>
                            <Image source={require('~/assets/home/edit.png')} style={styles.editIcons} />
                        </Pressable>
                        <View style={[styles.row, styles.between, { flexWrap: 'wrap' }]}>
                            <View style={styles.list}>
                                <Text style={styles.list_title}>{t('SportData.t9')}</Text>
                                <View style={{ marginVertical: px2dp(24) }}>
                                    <ProgressBarBySport
                                        progress={stepProGress}
                                        height={px2dp(120)}
                                        width={(width - px2dp(160)) / 2}
                                    />
                                    <View style={[styles.row, styles.between, { marginTop: px2dp(24) }]}>
                                        <Text style={styles.t1}>0</Text>
                                        <Text style={styles.t1}>{stepInfo.goal}</Text>
                                    </View>
                                </View>
                                <View style={[styles.row]}>
                                    <Text style={styles.title}>{stepInfo.steps}</Text>
                                    <Text style={styles.t2}>{t('SportData.t10')}</Text>
                                </View>
                            </View>
                            <View style={styles.list}>
                                <Text style={styles.list_title}>{t('SportData.t11')}</Text>
                                <View style={{ marginVertical: px2dp(24) }}>
                                    <ProgressBarBySport
                                        progress={caloriesProGress}
                                        height={px2dp(120)}
                                        width={(width - px2dp(160)) / 2}
                                        color="#F9AB8A"
                                        backgroundColor="#FCD9C9"
                                    />
                                    <View style={[styles.row, styles.between, { marginTop: px2dp(24) }]}>
                                        <Text style={styles.t1}>0</Text>
                                        <Text style={styles.t1}>{stepInfo.goalCalories}</Text>
                                    </View>
                                </View>
                                <View style={[styles.row]}>
                                    <Text style={styles.title}>{stepInfo?.calories}</Text>
                                    <Text style={styles.t2}>kcal</Text>
                                </View>
                            </View>
                            <View style={styles.list}>
                                <Text style={styles.list_title}>{t('SportData.t12')}</Text>
                                <View style={{ marginVertical: px2dp(24) }}>
                                    <View style={styles.row}>
                                        <Text style={[styles.title, { marginRight: px2dp(12) }]}>
                                            {stepInfo.time?.hours}
                                        </Text>
                                        <Text style={styles.t2}>h</Text>
                                        <Text style={[styles.title, { marginHorizontal: px2dp(12) }]}>
                                            {stepInfo?.time?.minutes}
                                        </Text>
                                        <Text style={styles.t2}>m</Text>
                                    </View>
                                </View>
                            </View>
                            <View style={styles.list}>
                                <Text style={styles.list_title}>{t('SportData.t13')}</Text>
                                <View style={{ marginVertical: px2dp(24) }}>
                                    <Text style={styles.title}>
                                        {stepInfo?.distance} <Text style={styles.t2}>km</Text>
                                    </Text>
                                </View>
                            </View>
                        </View>
                    </View>
                ) : (
                    <View>
                        <View style={[styles.card, styles.card1]}>
                            <View style={[styles.row, { justifyContent: 'space-around' }]}>
                                <View>
                                    <View style={[styles.row, { marginBottom: px2dp(16) }]}>
                                        <Image
                                            style={styles.icons1}
                                            source={{ uri: 'https://line.shbjy.cn/wxdata/imgs/stepSum.png' }}
                                        />
                                        <Text style={styles.card_title}>{t('SportData.t14')}</Text>
                                    </View>
                                    <View style={styles.row}>
                                        <Text style={styles.goalSteps}>{stepDatas.sum}</Text>
                                        <Text style={styles.t2}>{t('SportData.t10')}</Text>
                                    </View>
                                </View>
                                <View>
                                    <View style={[styles.row, { marginBottom: px2dp(16) }]}>
                                        <Image
                                            style={styles.icons1}
                                            source={{ uri: 'https://line.shbjy.cn/wxdata/imgs/stepSum.png' }}
                                        />
                                        <Text style={styles.card_title}>{t('SportData.t15')}</Text>
                                    </View>
                                    <View style={styles.row}>
                                        <Text style={styles.goalSteps}>{stepDatas.max}</Text>
                                        <Text style={styles.t2}>{t('SportData.t10')}</Text>
                                    </View>
                                </View>
                            </View>
                            <View style={[styles.row, { justifyContent: 'space-around', marginTop: px2dp(44) }]}>
                                <View>
                                    {activeIndex == 2 ? (
                                        <Text style={[styles.card_title, { marginBottom: px2dp(16) }]}>
                                            {t('SportData.t16')}
                                        </Text>
                                    ) : (
                                        <Text style={[styles.card_title, { marginBottom: px2dp(16) }]}>
                                            {t('SportData.t17')}
                                        </Text>
                                    )}
                                    <View style={[styles.row]}>
                                        <Text style={styles.goalSteps}>{stepDatas.lastAvg}</Text>
                                        <Text style={styles.t2}> {t('SportData.t10')}</Text>
                                    </View>
                                </View>
                                <View>
                                    {activeIndex == 2 ? (
                                        <Text style={[styles.card_title, { marginBottom: px2dp(16) }]}>
                                            {t('SportData.t18')}
                                        </Text>
                                    ) : (
                                        <Text style={[styles.card_title, { marginBottom: px2dp(16) }]}>
                                            {t('SportData.t19')}
                                        </Text>
                                    )}
                                    <View style={[styles.row]}>
                                        <Text style={[styles.goalSteps]}>{stepDatas.avg}</Text>
                                        <Text style={styles.t2}> {t('SportData.t10')}</Text>
                                    </View>
                                </View>
                            </View>
                        </View>
                        <View style={[styles.row, [{ alignSelf: 'center' }]]}>
                            <Pressable onPress={handlePrev}>
                                <Icon name={'chevron-back-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                            </Pressable>
                            <Text style={styles.selectDay}>{displayText}</Text>
                            <Pressable onPress={handleNext}>
                                <Icon name={'chevron-forward-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                            </Pressable>
                        </View>
                        <View style={{ width: '100%', height: px2dp(600) }}>
                            <ECharts option={stepOption} height={px2dp(600)} />
                        </View>
                        <View style={{ width: '100%', height: px2dp(600), marginTop: px2dp(64) }}>
                            <ECharts option={caloriesOption} height={px2dp(600)} />
                        </View>
                    </View>
                )}
            </View>
            <Modal
                isVisible={visible}
                presentationStyle="overFullScreen"
                onBackdropPress={() => setVisible(false)}
                statusBarTranslucent
                hasBackdrop>
                <View style={styles.modalContainer}>
                    <Text style={styles.modalTitle}>设置目标步数</Text>
                    <View style={[styles.input]}>
                        <TextInput
                            style={styles.inputStyle}
                            placeholder={'设置目标步数'}
                            returnKeyType={'done'}
                            value={number}
                            keyboardType="numeric"
                            maxLength={7}
                            onChangeText={(val) => {
                                setNumber(val);
                            }}
                            placeholderTextColor={'#a4a4a4'}
                        />
                    </View>
                    <Pressable style={[styles.bootom_button, styles.bt]} onPress={saveSportGoal}>
                        <Text style={styles.bootom_buttonText}>确认</Text>
                    </Pressable>
                </View>
            </Modal>
        </ScrollView>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '50%',
        marginHorizontal: px2dp(24),
    },
    nav: {
        backgroundColor: 'rgba(255, 255, 255, 0.12)',
        flexDirection: 'row',
        alignItems: 'center',
        height: px2dp(80),
        borderRadius: px2dp(99999),
        justifyContent: 'center',
        position: 'relative',
        marginBottom: px2dp(32),
    },
    listTable: {
        height: px2dp(80),
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: px2dp(12),
        borderRadius: px2dp(99999),
        width: tabWidth,
    },
    listTableText: {
        color: '#fff',
        fontSize: scale(28),
    },
    content: {
        flexGrow: 1,
        marginTop: px2dp(32),
    },
    card: {
        backgroundColor: 'rgba(216, 216, 216, 0.32)',
        borderRadius: px2dp(24),
        paddingVertical: px2dp(24),
        shadowOpacity: 0.06,
        shadowRadius: 8,
        elevation: 3,
        marginBottom: px2dp(32),
        padding: px2dp(24),
    },
    icons: {
        width: px2dp(80),
        height: px2dp(80),
    },
    t1: {
        color: '#a4a4a4',
        fontSize: scale(28),
    },
    goalSteps: {
        fontWeight: 'bold',
        color: '#fff',
        fontSize: scale(40),
        textAlign: 'center',
    },
    tips: {
        color: '#a4a4a4',
        fontSize: scale(28),
        marginLeft: px2dp(24),
    },
    editIcons: {
        width: px2dp(50),
        height: px2dp(50),
        tintColor: '#fff',
    },
    modalContainer: {
        padding: px2dp(24),
        backgroundColor: '#fff',
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(22),
    },
    input: {
        borderWidth: 1,
        borderColor: '#eee',
        borderRadius: px2dp(16),
        paddingHorizontal: px2dp(16),
        height: px2dp(100),
        justifyContent: 'center',
        marginTop: px2dp(16),
    },
    inputStyle: {
        color: '#000',
        fontSize: scale(28),
    },
    modalTitle: {
        color: '#000',
        textAlign: 'center',
        fontSize: scale(30),
        marginBottom: px2dp(32),
    },
    bt: {
        backgroundColor: '#242D56',
        borderColor: '#242D56',
        marginTop: px2dp(32),
    },
    bootom_button: {
        backgroundColor: '#242D56',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(999),
        height: px2dp(100),
        marginHorizontal: px2dp(32),
    },
    bootom_buttonText: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    list: {
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(48),
        padding: px2dp(24),
        width: (width - px2dp(80)) / 2,
        marginBottom: px2dp(24),
    },
    list_title: {
        color: '#fff',
        fontWeight: 'bold',
        fontSize: scale(32),
    },
    title: {
        color: '#fff',
        fontSize: scale(50),
        fontWeight: 'bold',
    },
    t2: {
        color: '#a4a4a4',
        fontSize: scale(26),
        marginLeft: px2dp(16),
    },
    selectDay: {
        fontSize: scale(32),
        marginHorizontal: px2dp(24),
        color: '#fff',
        fontWeight: 'bold',
    },
    card1: {
        marginBottom: px2dp(64),
    },
    card_title: {
        color: '#d4d4d4',
        fontSize: scale(30),
        textAlign: 'center',
    },
    icons1: {
        width: px2dp(40),
        height: px2dp(40),
        marginRight: px2dp(12),
    },
});
